<template>
  <div>
    <div class="header">
      <div class="header-title">
        <div class="header-btn">
          <i class="icon-back"></i>
          <el-button
            type="text"
            class="return_btn"
            @click="$router.push('/course')">返回</el-button>
        </div>
        <div class="title-name">
          新增课程
        </div>
      </div>
      <el-button type="primary">添加阶段</el-button>
    </div>
    <el-card>
      <el-tree
        :data = "sections"
        :props="defaultProps"
        draggable
        :allow-drop="handleDropItem"
        @node-drop="resetDropItemSort" >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <!-- 树父 -->
          <span v-if="data.sectionName">
            <el-button @click.stop="editSection">编辑</el-button>
            <el-button type="primary" @click.stop="addLesson(data)">添加课时</el-button>
            <el-select
              class="select-status"
              v-model="data.status"
              placeholder="请选择"
              @change="handleSectionStatusChange(data)"
            >
              <el-option label="已隐藏" :value="0" />
              <el-option label="待更新" :value="1" />
              <el-option label="已更新" :value="2" />
            </el-select>
          </span>
          <!-- 树子 -->
          <span v-else>
            <el-button @click.stop="editLesson(data,node.parent.data)">编辑</el-button>
            <el-button type="success" @click.stop="$router.push({
              name:'video',
              params:{courseId},
              query:{
                sectionId:node.parent.data.id,
                lessonId:data.id
              }
            })">上传视频</el-button>
            <el-select
              class="select-status"
              v-model="data.status"
              placeholder="请选择"
              @change="handleLessonStatusChange(data)"
            >
              <el-option label="已隐藏" :value="0" />
              <el-option label="待更新" :value="1" />
              <el-option label="已更新" :value="2" />
            </el-select>
          </span>
        </span>
      </el-tree>
    </el-card>
    <!-- 章节 -->
    <el-dialog
      title="章节信息"
      :visible.sync="isAddSectionShow"
      width="34%"
      :before-close="handleCloseSec">
      <el-form ref="section-form" :model="section" label-width="100px">
        <el-form-item label="课程名称">
          <el-input
            :value="course.courseName"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="章节名称" prop="sectionName">
          <el-input v-model="section.sectionName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="章节描述" prop="description">
          <el-input v-model="section.description" type="textarea" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="章节排序" prop="orderNum">
          <el-input-number v-model="section.orderNum"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddSectionShow = false">取 消</el-button>
        <el-button type="primary" @click="isAddSectionShow = false">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 课时 -->
    <el-dialog
      title="课时基本信息"
      :visible.sync="isAddLessonShow"
      width="40%"
      :before-close="handleCloseLes">
      <el-form ref="lesson-form" :model="lesson" label-width="100px">
        <el-form-item label="课程名称">
          <el-input
            :value="course.courseName"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="章节名称" prop="sectionName">
          <el-input
            :value="lesson.sectionName"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="课时名称" prop="theme">
          <el-input v-model="lesson.theme" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="时长" prop="duration">
          <el-input v-model.number="lesson.duration" type="number" autocomplete="off">
            <template slot="append">分钟</template>
          </el-input>
        </el-form-item>
        <el-form-item label="是否开放试听" prop="isFree">
          <el-switch v-model="lesson.isFree"></el-switch>
        </el-form-item>
        <el-form-item label="课时排序" prop="orderNum">
          <el-input-number v-model="lesson.orderNum">
            <template slot="append">数字控制排序，数字越大越靠后</template>
          </el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddLessonShow = false">取 消</el-button>
        <el-button type="primary" @click="isAddLessonShow = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { getCourseById, getSectionAndLesson, saveOrUpdateLesson, saveOrUpdateSection } from '@/services/courses'
import Vue from 'vue'
// 课course->章节section->课时lesson
export default Vue.extend({
  name: 'Section',
  props: {
    courseId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    const section = {
      courseId: this.courseId,
      sectionName: '',
      description: '',
      orderNum: 0,
      status: 0
    }

    const lesson = {
      courseId: this.courseId,
      sectionId: undefined,
      sectionName: '',
      theme: '',
      duration: 0,
      isFree: false,
      orderNum: 0,
      status: 0
    }

    return {
      sections: [],
      course: {},
      defaultProps: {
        children: 'lessonDTOS',
        label (data:any, node:any) {
          return data.sectionName || data.theme
        }
      },
      isAddSectionShow: false,
      section,
      isAddLessonShow: false,
      lesson
    }
  },
  methods: {
    async loadSectionAndLesson () {
      const { data } = await getSectionAndLesson(this.courseId)
      console.log('章节', data)
      this.sections = data.data
    },
    async loadCourseById () {
      const { data } = await getCourseById(this.courseId)
      console.log('课', data)
      this.course = data.data
    },

    // 章节编辑和关闭
    handleCloseSec () {
      this.isAddSectionShow = false
    },
    editSection () {
      // console.log(data)
      this.section = { // 防止数据还是编辑时获取的数据
        courseId: this.courseId,
        sectionName: '',
        description: '',
        orderNum: 0,
        status: 0
      }
      this.isAddSectionShow = true
    },
    // ==========================

    // 课程编辑和关闭
    handleCloseLes () {
      this.isAddLessonShow = false
    },
    addLesson (data:any) {
      this.lesson = {
        sectionName: data.sectionName,
        sectionId: data.id,
        courseId: this.courseId,
        theme: '',
        duration: 0,
        isFree: false,
        orderNum: 0,
        status: 0
      }
      this.isAddLessonShow = true
    },
    // ==========================

    // 更新
    handleSectionStatusChange (data:any) {
      console.log(data)
    },

    handleLessonStatusChange (data:any) {
      console.log(data)
    },
    // ==========================

    // 子项
    editLesson (lesson:any, section:any) {
      this.lesson = lesson
      this.lesson.sectionName = section.sectionName
      this.isAddLessonShow = true
    },

    /**
     * @param draggingNode 拖拽节点
     * @param dropNode 到达节点
     * @param type 'prev'、'inner' 和 'next'，分别表示放置在目标节点前、插入至目标节点和放置在目标节点后
    */
    handleDropItem (draggingNode:any, dropNode:any, type:any) {
      // 只有子项有sectionId且每个列表下的sectionId相同，父项都是undefined
      return draggingNode.data.sectionId === dropNode.data.sectionId && type !== 'inner'
    },
    async resetDropItemSort (draggingNode:any, dropNode:any, type:any, event:any) {
      try {
        console.log(draggingNode.parent.childNodes)
        // let arr = this.sections
        // if (draggingNode.data.lessonDTOS) { // 章节
        //   await Promise.all(arr.map((item:any, index:number) => {
        //     return saveOrUpdateSection({
        //       id: item.data.id,
        //       orderNum: index + 1
        //     })
        //   }))
        // } else { // 章节子项课时
        //   //
        //   arr = arr.filter((item:any) => item.lessonDTOS.filters((iitem:any) => iitem.id === draggingNode.data.id)[0])
        //   await Promise.all((arr[0] as any).lessonDTOS.map((item:any, index:number) => {
        //     return saveOrUpdateLesson({
        //       id: item.data.id,
        //       orderNum: index + 1
        //     })
        //   }))
        // }

        // await Promise.all(draggingNode.parent.childNodes.map((item:any, index:number) => {
        //   if (draggingNode.data.lessonDTOS) { // 章节包含课时，此字段表示章节
        //     return saveOrUpdateSection({
        //       id: item.data.id,
        //       orderNum: index + 1
        //     })
        //   } else {
        //     return saveOrUpdateLesson({
        //       id: item.data.id,
        //       orderNum: index + 1
        //     })
        //   }
        // }))
        this.$message.error('排序成功')
      } catch (e) {
        this.$message.error('排序失败')
      }
    }
  },
  created () {
    this.loadSectionAndLesson()
    this.loadCourseById()
  }
})
</script>

<style lang="scss" scoped>
.header{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
  .header-title{
    display: flex;
    // line-height: 38px;
    align-items: center;
    .header-btn{
      position: relative;
      display: flex;
      margin-right: 40px;
      .icon-back{
        font-size: 18px;
        margin-right: 6px;
        align-self: center;
      }
      .icon-back:before{
        content: '←';
      }
      .return_btn{
        font-size: 14px;
        font-weight: 500;
      }
      .return_btn:after{
        content: "";
        position: absolute;
        width: 1px;
        height: 16px;
        right: -20px;
        top: 50%;
        transform: translateY(-50%);
        background-color: #dcdfe6;
      }
    }
    .title-name{
      width: 100px;
    }
  }
}

::v-deep .el-tree-node__content {
  height: auto;
}
.custom-tree-node {
  flex: 1; // flex-grow:1
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding: 8px;
  border-bottom: 1px solid #ebeef5;
}
.select-status{
  margin-left: 10px;
}
</style>
